<template>
  <el-container style="height: 100%; padding: 10px">
    <el-aside width="550px" style="padding: 20px">
      <el-card :body-style="{ overflow: 'auto' }">
        <div style="height: calc(100vh - 120px)">
          <user-card v-model:user-data="qrCodeInfo"  type="gun"/>
          <br />
          <bluetooth v-model="hw700" @save="handleRecordSave" />
          <br />
        </div>
      </el-card>
    </el-aside>
    <el-main>
      <el-card :body-style="{ overflow: 'auto' }">
        <div style="height: calc(100vh - 120px)">
          <el-form :model="searchForm" :inline="true">
            <el-form-item label="日期">
              <el-date-picker
                v-model="searchForm.measureTime"
                :clearable="false"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
              />
            </el-form-item>
            <el-form-item label="姓名/身份证">
              <el-input v-model="searchForm.name" clearable />
            </el-form-item>
            <el-form-item>
              <el-button type="warning" @click="handleSearch">搜索</el-button>
              <el-button
                type="warning"
                @click="handleSynchronous"
                :loading-icon="Eleme"
                :loading="synchronousStatus"
                >同步</el-button
              >
            </el-form-item>
          </el-form>

          <el-table :data="tableData" :style="{ height: 'calc(100% - 130px)' }">
            <el-table-column prop="userName" label="姓名" />
            <el-table-column prop="cardId" label="身份证" />
            <el-table-column prop="sex" label="性别">
              <!--              <template #default="{ row }">-->
              <!--                {{ row.sex === "1" ? "男" : "女" }}-->
              <!--              </template>-->
            </el-table-column>
            <el-table-column prop="article" label="项目" />
            <el-table-column prop="height" label="身高" />
            <el-table-column prop="weight" label="体重" />
            <el-table-column prop="bim" label="体质" />
            <el-table-column prop="waistline" label="腰围" />
            <el-table-column
              prop="measureTime"
              label="测量时间"
              :formatter="timeFormatter"
            />
          </el-table>
          <el-pagination
            v-model:currentPage="tableProps.pagination.currentPage"
            v-model:page-size="tableProps.pagination.pageSize"
            :page-sizes="[2, 10, 20, 50]"
            layout="sizes, prev, pager, next, jumper"
            :total="tableProps.pagination.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </el-main>
  </el-container>
</template>

<script lang="ts" setup>
import {
  IHW700TableProps,
  ISearchParams,
} from "@/model/BloodType";
import { Eleme } from "@element-plus/icons-vue";
import { computed, reactive, ref, toRaw, watch } from "vue";
import dayjs from "dayjs";
import { ElMessage, ElNotification } from "element-plus";
// import request from "@/request"
import UserCard from "@/components/UserCard/index.vue";
import Bluetooth from "./Bluetooth.vue";
import { hwUtils } from "@/utils/";
import { db, DbService } from "@/db/db";
import { createQRCodeInfo, IQRCodeInfo } from "@/model/IQRCodeInfo";
import { asyncHWData } from "@/api/asyncApi";
import {createHw700, Ihw700Cloud} from "@/model/TerminalType";
const timeFormatter = (row, column, cellValue) => {
  if (cellValue) {
    return dayjs(cellValue).format("YYYY-MM-DD HH:mm:ss");
  }
  return "";
};
// 扫码得到的用户信息
const qrCodeInfo = ref<Partial<IQRCodeInfo>>(createQRCodeInfo());
const hw700 = ref<Partial<Ihw700Cloud>>(createHw700());

const dbService = new DbService<Partial<Ihw700Cloud>>(db.hw700);

/**同步 */
const synchronousStatus = ref(false);
const handleSynchronous = async () => {
  synchronousStatus.value = true;
  try {
    const rows = await db.hw700.where("synchronous").equals(0).toArray();
    if (rows.length === 0) {
      ElMessage.closeAll();
      ElMessage.info("暂无可同步的数据！");
      return;
    }
    const asyncRow = rows.map((item) => {
      item.data_id = item.id;
      delete item.id;
      return item;
    });
    const data: any = await asyncHWData({ data: asyncRow });
    ElMessage.success({
      message:
        "成功" + data.successes.length + "条,失败：" + data.fails.length + "条",
    });
    console.log(data);
    if (data && data.successes.length) {
      data.successes.map(async (item) => {
        console.log(item.data_id);
        await db.hw700.update(item.data_id, { synchronous: 1 });
      });
    }
  } catch (e: any) {
    ElMessage.closeAll();
    ElMessage.error("同步失败" + e.msg);
  } finally {
    synchronousStatus.value = false;
  }
};
/**
 * 列表功能，包括搜索
 */
/**------------搜索功能开始----------------- */
const searchForm = ref<ISearchParams>({
  measureTime: [dayjs().startOf("D").valueOf(), dayjs().endOf("d").valueOf()],
  name: "",
});
const tableProps = reactive<IHW700TableProps>({
  pagination: {
    currentPage: 1,
    pageSize: 20,
    total: 0,
  },
});
const searchFormResult = ref({
  name: searchForm.value.name,
  measureTime: searchForm.value.measureTime,
});
const handleSearch = () => {
  searchFormResult.value.name = searchForm.value.name;
  searchFormResult.value.measureTime = searchForm.value.measureTime;
};

const searchData = computed(() => {
  return {
    name: searchFormResult.value.name,
    measureTime: searchFormResult.value.measureTime,
    limit: tableProps.pagination.pageSize,
    offset:
      (tableProps.pagination.currentPage - 1) * tableProps.pagination.pageSize,
  };
});
const tableData = ref<Array<Partial<Ihw700Cloud>>>([]);
watch(
  searchData,
  async (search) => {
    const data = await queryService(toRaw(search));
    tableData.value = data;
  },
  {
    immediate: true,
  }
);
async function queryService(searchItem) {
  const data = await db.hw700
    .where("measureTime")
    .between(
      dayjs(searchItem.measureTime[0]).valueOf(),
      dayjs(searchItem.measureTime[1]).valueOf()
    )
    .filter((item) => {
      if (!searchItem.name) {
        return true;
      }
      if (item.userName && item.userName.indexOf(searchItem.name) !== -1) {
        return true;
      }
      if (item.cardId && item.cardId.indexOf(searchItem.name) !== -1) {
        return true;
      }
      return false;
    })
    .offset(searchItem.offset)
    .limit(searchItem.limit)
    .reverse()
    .toArray();
  return data;
}

const handleRecordSave = async () => {
  if (!qrCodeInfo.value?.idno) {
    ElNotification({
      title: "保存错误",
      message: "无人员信息，不能保存",
      type: "error",
    });
    return;
  }
  if (!hw700.value?.height || !hw700.value?.weight) {
    ElNotification({
      title: "错误",
      message: "无身高体重信息，不能保存",
      type: "error",
    });
    return;
  }
  if (hw700.value.height && hw700.value.weight) {
    hw700.value.bim = hwUtils.getBMI(hw700.value.height, hw700.value.weight);
    hw700.value.waistline = hwUtils.getWaistline(
      hw700.value.height,
      hw700.value.sex
    );
    hw700.value.article = "身高体重";
  }
  try {
    const result:any=await dbService.saveCard(toRaw(hw700.value),toRaw(qrCodeInfo.value));
    ElMessage.success(result.message)
    qrCodeInfo.value = {};
    hw700.value = {};
    tableData.value = await queryService(toRaw(searchData.value));
  }catch (e) {
  }
};
/**------------搜索功能结束----------------- */

const handleSizeChange = () => {};
const handleCurrentChange = () => {};
</script>
<style scoped lang="scss">
html,
body {
  height: 100%;
}

.el-main {
  padding: 0;
}
</style>
